package cn.xyt.server;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.xyt.util.DeviceCache;
import cn.xyt.util.NettyContextUtil;

@Sharable
public class HeartHandler extends ChannelInboundHandlerAdapter {
	private final Logger logger = LoggerFactory.getLogger(HeartHandler.class);
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        /*心跳处理*/
		if (evt instanceof IdleStateEvent) {
			String id = (String)NettyContextUtil.getAttr(ctx, "id");
			ctx.close();
			//logger.error("userEventTriggered ctx.close id = {}" , id);
        }
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		super.channelRegistered(ctx);
	}
	
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) {
		// 业务处理 
		String id = (String)NettyContextUtil.getAttr(ctx, "id");
		DeviceCache.remove(id);
		//logger.error("channelInactive DeviceCache.remove id = {}" , id);
	}
}
